import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:edu_assistant/api/data_service.dart';

class UploadFilePage extends StatefulWidget {
  @override
  _UploadFileState createState() => _UploadFileState();
}

class _UploadFileState extends State<UploadFilePage> with AutomaticKeepAliveClientMixin {
  String? _selectedFilePath;
  String? _uploadedUrl; // 用于存储上传后的文件地址;
  @override
  void initState() {
    super.initState();
  }

  /**
   * 选择文件上传
   */
  Future pickFile() async {
    setState(() {
      this._selectedFilePath = "";
      this._uploadedUrl="";
    });
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result!= null && result.files.isNotEmpty) {
      setState(() {
        this._selectedFilePath = result.files.first.path;
      });
      PlatformFile file = result.files.first;
      String  fileUrl = await DataService.uploadFile(file.path!,resultRecive);
      setState(() {
        this._uploadedUrl = fileUrl;
      });
    }
  }

  resultRecive(fileUrl){
    setState(() {
      this._uploadedUrl = fileUrl;
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 文件选择按钮
            ElevatedButton(
              onPressed: pickFile,
              child: const Text('选择文件'),
            ),
            const SizedBox(height: 20),
            // 显示已选择的文件路径（如果有）
            if (_selectedFilePath!= null)
              Text(
                '已选择文件: ${_selectedFilePath}',
                style: const TextStyle(fontSize: 16),
              ),
            const SizedBox(height: 20),
            // 上传完成后显示上传地址（如果有）
            if (_uploadedUrl!= null)
              Text(
                '上传地址: ${_uploadedUrl}',
                style: const TextStyle(fontSize: 16, color: Colors.green),
              ),
          ],
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
